package com.seestech.sell.web.agent;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.seestech.sell.common.annotation.Duplicate;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.JsonUtils;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.domain.model.Area;
import com.seestech.sell.domain.model.ResultBean;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.domain.model.enums.StatusEnums;
import com.seestech.sell.service.IAreaService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

import static com.seestech.sell.common.utils.ResponseUtils.writeErrorResponse;
import static org.apache.shiro.web.filter.mgt.DefaultFilter.rest;
import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;


/**
 * Created by idiot on 2017/6/19.
 */
@Controller
@RequestMapping(value = "area")
public class AreaController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(AreaController.class);

    @Resource
    private IAreaService areaService;

    //加载page页面
    @RequiresPermissions(value = "area:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(Model model){
        logger.info("加载区域页面信息=====》》》");
        return "area/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, Area info, Model model){
        User user = getUser();
        if(user == null){
            logger.error("获取品牌信息======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        //获取这个用户所在企业相关的用户信息
        Set<Long> userIds = getUserIds(user);
        userIds.add(user.getUserId());
        info.setUserIds(userIds);
        info.setCreateUser(null);
        info.setStatus(StatusEnums.VALID.getValue());
        Page<Area> lists = areaService.getAllAreas(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", lists);
        return "area/data";
    }

    //加载编辑页面
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model){
        return "area/update";
    }

    //编辑信息
    @Duplicate
    @RecordLog(value = "修改区域信息")
    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Object update(Area info){
        User user = getUser();
        if (user == null){
            logger.error("用户信息已经失效");
            return ResponseUtils.responseError("无效的用户信息，请重新登录");
        }
        // 根据名称获取区域信息
        List<Area> areas = areaService.getAreasByName(info.getName());
        //areaId为空/0时表示   新增操作
        if(info.getAreaId() == null){
            if (areas != null && areas.size() > 0){
                return ResponseUtils.responseError("新增区域信息失败，该名称已经存在");
            }
            info.setCreateUser(user.getUserId());
            areaService.insert(info);
            return ResponseUtils.responseSuccess("新增区域信息成功");
        }else {     //修改操作
            if (areas != null && areas.size() == 1){
                // 获取第一个  判断主键是否相同
                Area area = areas.get(0);
                if(!area.getAreaId().equals(info.getAreaId())) {
                    return ResponseUtils.responseError("修改区域信息失败,该名称已经存在");
                }
            }else if (areas != null && areas.size() > 1){
                return ResponseUtils.responseError("修改区域信息失败，该名称已经存在");
            }
            info.setUpdateUser(user.getUserId());
            areaService.update(info);
            return ResponseUtils.responseSuccess("修改区域信息成功");
        }
    }


    //加载编辑页面
    @RequestMapping(value = "{areaId}/toUpdate", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("areaId") Long areaId, Model model){
        Area area = areaService.getAreaByAreaId(areaId);
        model.addAttribute("area",area);
        return "area/update";
    }

    //删除品牌信息
    @RecordLog(value = "删除区域信息")
    @RequestMapping(value = "{areaId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("areaId") Long areaId){
        areaService.delete(areaId);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"删除区域信息成功");
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] areaIds){
        areaService.deleteBatch(areaIds);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"批量删除区域信息成功");
    }

    /*******************************/

    /**
     * @description  区域信息接口
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAreas.json")
    public Object getAreas(){
        logger.info("获取区域信息接口========>>>>>>>>>>>开始");
        ResultBean<Object> resultBean;
        Area area = new Area();
        area.setStatus(StatusEnums.VALID.getValue());
        List<Area> areas = areaService.getAreas(area);
        //json  过滤
        JSONArray object = JsonUtils.parseArray(areas);
        resultBean = ResponseUtils.initResultBean(object, Constants.ResponseCode.success, "成功", true);
        resultBean.setTotalCount(areas.size());
        logger.info("获取区域信息接口========>>>>>>>>>>>结束");
        return resultBean;
    }
}
